﻿#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.ServiceProcess;

using octalforty.Chinchillin.Shared.Deployment;
using octalforty.Chinchillin.Shared.Deployment.Metadata;

namespace octalforty.Chinchillin.Actions.Scm
{
    [Action(Name, RollbackAction = "scm:stop-service")]
    public class StartServiceAction : ActionBase
    {
        #region Private Constants
        private const string Name = "start-service";

        private static readonly ActionInfo actionInfo = new ActionInfo
            {
                Name = Name,
                Description = Resources.Scm.StartServiceActionDescription,
                Arguments = new[] {
                    new ActionArgumentInfo("service", ActionArgumentType.Uri) { Description = Resources.Scm.ServiceAction_ServiceArgumentDescription },
                    new ActionArgumentInfo("timeout", ActionArgumentType.String) { Description = "" }
                }
            };
        #endregion

        public StartServiceAction() :
            base(actionInfo)
        {
        }

        public override void Execute(IActionExecutionContext executionContext)
        {
            var service = (Uri)executionContext.Arguments["service"];
            var timeoutValue = executionContext.Arguments.ContainsKey("timeout") ?
                (string)executionContext.Arguments["timeout"] :
                "30";

            var timeout = TimeSpan.Parse(timeoutValue.Contains(":") ? timeoutValue : "00:00:" + timeoutValue);

            var serviceController = new ServiceController(service.Authority);

            TracingManager.TraceEvent(executionContext, TraceEventType.Information, 0, 
                string.Format("Current '{0}' service status: {1}", serviceController.DisplayName, serviceController.Status));

            if(serviceController.Status == ServiceControllerStatus.Running) return;

            try
            {
                TracingManager.TraceEvent(executionContext, TraceEventType.Information, 0, string.Format("Starting '{0}' with timeout of {1}", serviceController.DisplayName, timeout));
                serviceController.Start();
                serviceController.WaitForStatus(ServiceControllerStatus.Running, timeout);
            } // try
            catch(Exception e)
            {
                TracingManager.TraceEvent(executionContext, TraceEventType.Information, 0, 
                    string.Format("Could not start '{0}': {1}", serviceController.DisplayName, e));
            } // catch

            TracingManager.TraceEvent(executionContext, TraceEventType.Information, 0, 
                string.Format("Current '{0}' service status: {1}", serviceController.DisplayName, serviceController.Status));
        }
    }
}
